package com.export.document.service;

import com.export.document.entity.ExportRecord;
import com.export.document.repository.ExportRecordRepository;
import com.export.document.util.ExcelUtil;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ExportDocService {
    @Autowired
    private ReadDBService readService;
    @Autowired
    private ExportRecordRepository recordRepository;

    /**
     * 导出数据字典
     *
     * @param shcemaName
     * @param tableName
     */
    public Workbook exportDoc(String shcemaName, String tableName) {
        List<Object[]> tables = null;
        if (!StringUtils.isEmpty(tableName)) {
            List<Object[]> tbs = recordRepository.findTablesByShcemaNameAndTableName(shcemaName, tableName);
            tables = tbs;
        } else {
            List<Object[]> tbs = recordRepository.findTablesByShcemaName(shcemaName);
            tables = tbs;
        }
        XSSFWorkbook wb = new XSSFWorkbook();
        ExcelUtil.createCatalogue(wb, tables);
        String[] titles1 = new String[]{"表名", "描述"};
        String[] titles2 = new String[]{"列名", "类型", "长度", "是否为NULL", "说明"};
        tables.stream().forEach(e -> {
            String sheetName = e[1].toString();
            String sheetNameEn = e[0].toString();
            List<Map<String, Object>> columns = readService.readColumns(shcemaName, sheetNameEn);
            ExcelUtil.createSheet(wb, sheetName, sheetNameEn, titles1, titles2, columns);
        });
        return wb;
    }

    public void save(String fileName) {
        ExportRecord record = new ExportRecord();
        record.setCreateTime(new Date());
        record.setFileName(fileName);
        record.setResult("0");
        record.setReason("生成数据字典");
        recordRepository.save(record);
    }
}
